/**
 * 
 */
package adnotatio.rdf;

import java.io.Serializable;
import java.util.Collection;

/**
 * This is a common super-class for all entries.
 * 
 * @author kotelnikov
 */
public abstract class Entity implements Serializable {
    /**
     * The datamodel-owner of this entry.
     */
    protected Model fModel;

    /**
     * This constructor initializes the internal fields and sets the model
     * 
     * @param model the model to set
     */
    public Entity(Model model) {
        super();
        fModel = model;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof Entity))
            return false;
        Entity literal = (Entity) obj;
        return getStringValue().equals(literal.getStringValue());
    }

    /**
     * Returns the model managing this entry
     * 
     * @return the model managing this entry
     */
    public Model getModel() {
        return fModel;
    }

    /**
     * Returns a string representation of this entry
     * 
     * @return a string representation of this entry
     */
    protected abstract String getStringValue();

    /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return getStringValue().hashCode();
    }

    /**
     * This is an utility method transforming the given object to a
     * {@link PropertyValue} instance. It is used in subclasses to get
     * properties wrappers used to store values of properties. If the given
     * object is an instance of the {@link PropertyValue} type then this method
     * returns it "as is".
     * 
     * @param value the value to wrap
     * @return a property wrapper containing the given object
     */
    protected PropertyValue toPropertyValue(Object value) {
        PropertyValue result = null;
        if (value instanceof PropertyValue) {
            result = (PropertyValue) value;
        } else if (value instanceof ID) {
            Resource resource = fModel.getResource((ID) value, true);
            result = resource.getReference();
        } else if (value instanceof Resource) {
            result = ((Resource) value).getReference();
        } else if (value instanceof Collection) {
            Container container = fModel.newContainer();
            container.addAllValues((Collection) value);
            result = container;
        } else {
            result = fModel.newLiteral(value);
        }
        return result;
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return getStringValue();
    }
}
